<template>
  <div class="product-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增商品</span>
        </div>
      </template>

      <el-form 
        :model="productForm" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品图片" prop="imageUrl">
          <el-input v-model="productForm.imageUrl" placeholder="请输入图片链接" />
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0" 
            :precision="2" 
            :step="0.1" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="库存" prop="inventory">
          <el-input-number 
            v-model="productForm.inventory" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="销量" prop="sales">
          <el-input-number 
            v-model="productForm.sales" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="评论数" prop="comments">
          <el-input-number 
            v-model="productForm.comments" 
            :min="0" 
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="是否广告" prop="isAd">
          <el-switch 
            v-model="isAdSwitch" 
            active-text="是" 
            inactive-text="否"
            @change="handleAdChange"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch 
            v-model="statusSwitch" 
            active-text="上架" 
            inactive-text="下架"
            @change="handleStatusChange"
          />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-input v-model="productForm.tags" placeholder="请输入商品标签，多个标签用逗号分隔。例如：[&quot;小米&quot;, &quot;手机&quot;]" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            添加商品
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import productApi, { type ProductType } from '@/api/product'

// 表单引用
const formRef = ref()

// 路由和参数
const route = useRoute()
const router = useRouter()

// 表单数据
const productForm = ref<ProductType>({
  id: 0,
  name: '',
  imageUrl: '',
  price: 0,
  sales: 0,
  comments: 0,
  isAd: false,
  inventory: 0,
  status: 1,
  tags: ''
})

// 广告开关和状态开关（用于UI展示）
const isAdSwitch = ref(false)
const statusSwitch = ref(true)

// 提交按钮加载状态
const submitLoading = ref(false)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  inventory: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请输入商品标签', trigger: 'blur' }
  ]
}

// 处理广告开关变化
const handleAdChange = (val: boolean) => {
  productForm.value.isAd = val
}

// 处理状态开关变化
const handleStatusChange = (val: boolean) => {
  productForm.value.status = val ? 1 : 0
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 新增商品
        const res: any = await productApi.addProduct(productForm.value)
        
        if (res.data.code === 200) {
          ElMessage.success('添加商品成功')
          router.push('/product/list')
        } else {
          ElMessage.error(`添加商品失败: ${res.data.msg}`)
        }
      } catch (error) {
        ElMessage.error('添加商品失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  productForm.value = {
    id: 0,
    name: '',
    imageUrl: '',
    price: 0,
    sales: 0,
    comments: 0,
    isAd: false,
    inventory: 0,
    status: 1,
    tags: ''
  }
  isAdSwitch.value = false
  statusSwitch.value = true
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.product-add {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>